<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-form ref="form" label-width="90px" :rules="rules" :model="form">
          <div style="margin-bottom:20px">
            <el-form-item label="学科:" prop="subjectID">
              <el-select v-model="form.subjectID " placeholder="请选择" class="select">
                <el-option
                  v-for="item in option"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="margin-bottom:20px">
            <el-form-item label="目录:" prop="catalogID">
              <el-select v-model="form.catalogID" placeholder="请选择" class="select">
                <el-option
                  v-for="item in options_catalogID"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="margin-bottom:20px">
            <el-form-item label="企业:" prop="enterpriseID">
              <el-select v-model="form.enterpriseID" placeholder="请选择" class="select">
                <el-option
                  v-for="item in options_company"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="margin-bottom:20px">
            <el-form-item label="城市:" prop="province">
              <el-select v-model="form.province" placeholder="请选择" @change="changeCity()">
                <el-option v-for="item in options_city" :key="item" :value="item"></el-option>
              </el-select>
              <el-select v-model="form.city" placeholder="请选择" style="margin-left:17px">
                <el-option v-for="item in options_province" :key="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="margin-bottom:40px">
            <el-form-item label="方向:" prop="direction">
              <el-select v-model="form.direction" placeholder="请选择" class="select">
                <el-option
                  v-for="item in option"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="margin-bottom:40px">
            <el-form-item label="题型:">
              <el-radio-group v-model="questionType">
                <el-radio :label="1">单选</el-radio>
                <el-radio :label="2">多选</el-radio>
                <el-radio :label="3">简单题</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div style="margin-bottom:60px">
            <el-form-item label="难度:">
              <el-radio-group v-model="difficulty">
                <el-radio :label="1">简单</el-radio>
                <el-radio :label="2">一般</el-radio>
                <el-radio :label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div style="margin-bottom:40px">
            <el-form-item label="内容:" prop="question">
              <quill-editor :options="editorOption" v-model="form.question" v-on:blur="submit()"></quill-editor>
            </el-form-item>
          </div>
          <!-- </el-form> -->
          <div style="margin-bottom:40px">
            <!-- 单选 -->
            <ul style="margin-left:20px" v-if="questionType==1" v-on:click="pushImg">
              <el-radio-group v-model="radio">
                <li v-for="i in options" :key="i.id">
                  <el-radio :label="i.code" style="margin-right:0">
                    {{i.code}}:
                    <el-input placeholder="请输入内容" v-model="i.title" clearable></el-input>
                  </el-radio>
                  <input type="file" style="display:none" v-on:change="getUrl" />
                  <img alt="上传图片" title="上传图片" :src="i.img||cache_img" v-on:error='defaultUrl' />
                </li>
              </el-radio-group>
            </ul>
            <!-- 多选 -->
            <ul style="margin-left:20px" v-else-if="questionType==2" v-on:click="pushImg">
              <el-checkbox-group v-model="checkList">
                <li v-for="i in options" :key="i.code">
                  <el-checkbox :label="i.code">
                    {{i.code}}:
                    <el-input placeholder="请输入内容" v-model="i.title" clearable></el-input>
                  </el-checkbox>
                  <input type="file" style="display:none" v-on:change="getUrl" />
                  <img alt="上传图片" :src="i.img||cache_img" ref="img" v-on:error='defaultUrl' />
                </li>
              </el-checkbox-group>
            </ul>
            <el-row style="margin-left:55px">
              <el-button
                type="primary"
                :disabled="!(this.questionType==2)"
                v-if="this.questionType!=3"
                v-on:click="addItem"
              >+增加选项与答案</el-button>
            </el-row>
          </div>

          <!-- <el-form label-width="90px"> -->
          <el-form-item label="解析视频:">
            <el-input placeholder="请输入内容" v-model="videoURL" clearable style="width:500px"></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor :options="editorOption" v-model="form.answer" v-on:blur="submit()"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="remarks" style="width:460px"></el-input>
          </el-form-item>
          <el-form-item label="试题标签:">
            <el-select v-model="tags" placeholder="请选择" class="select" multiple>
              <el-option
                v-for="item in option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-row style="margin-top:20px">
              <el-button type="primary" v-on:click="submitForm()">确认提交</el-button>
            </el-row>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 富文本
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// ajax函数
import { createAPI } from '@/utils/request'
// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'

export default {
  name: 'question-new',
  components: {
    quillEditor
  },
  data () {
    return {
      cache_img: '',
      checkList: [],
      radio: '',
      options: [
        {
          code: 'A',
          title: '',
          isRight: '',
          img: ''
        },
        {
          code: 'B',
          title: '',
          isRight: '',
          img: ''
        },
        {
          code: 'C',
          title: '',
          isRight: '',
          img: ''
        },
        {
          code: 'D',
          title: '',
          isRight: '',
          img: ''
        }
      ],
      form: {
        subjectID: '',
        question: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '', // 城市
        direction: '', // 方向
        answer: '' // 答案
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入内容', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ],

        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ]
      },
      cache: '',
      tags: [], // 试题标签
      remarks: '', // 题目备注
      question: '', // 内容
      imgurl: '', // 图片地址
      options_province: '',
      options_company: '',
      options_city: '',
      options_catalogID: '',
      videoURL: '',
      option: '',
      questionType: 1,
      difficulty: 1,
      t_radio: 0,
      editorOption: {
        // 对富文本编辑器的配置
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      }
    }
  },
  async mounted () {
    // 获取id
    if (this.$route.query.id) {
      const { data } = await createAPI(
        '/questions/' + this.$route.query.id,
        'get'
      )
      // 学科
      this.subjectID = Number(data.subjectID)
      // 目录
      this.catalogID = data.catalogID
      // 企业
      this.form.enterpriseID = data.enterpriseID
      // 城市
      this.province = data.province
      this.city = data.city
      // console.log(this.city)
      // 方向
      this.direction = Number(data.direction)
      // 题型
      this.questionType = Number(data.questionType)
      // 难度
      this.difficulty = Number(data.difficulty)
      // 视频地址
      this.videoURL = data.videoURL
      // 答案
      this.form.answer = data.answer
      // 题目备注
      this.remarks = data.remarks
      // 试题标签
      this.tags = data.tags.split(',')
      // 内容
      this.question = data.question
      // 选项
      this.options = data.options.sort(
        (a, b) => a.code.charCodeAt(0) - b.code.charCodeAt(0)
      )
      // 选项赋值
      if (this.questionType !== 3) {
        this.questionType === 1
          ? this.options.forEach((i) => {
            if (i.isRight) {
              this.radio = i.code
            }
          })
          : this.options.forEach((i) => {
            if (i.isRight) {
              this.checkList.push(i.code)
            }
          })
      }
    }
    // 学科
    let res = await createAPI('/subjects/simple', 'get')
    this.option = res.data
    // 目录
    res = await createAPI('/directorys', 'get')
    this.options_catalogID = res.data.items.map((cur) => {
      return {
        value: cur.id,
        label: cur.directoryName
      }
    })
    // 公司
    res = await createAPI('/companys', 'get')
    this.options_company = res.data.items.map((cur) => {
      return {
        value: cur.id,
        label: cur.company
      }
    })
    // 城市
    this.options_city = provinces()

    this.cache_img =
      ''
    this.cache_img = URL.createObjectURL(this.dataURLtoBlob(this.cache_img))
    console.log(this.cache_img)
  },
  methods: {
    defaultUrl (e) {
      e.target.src = this.cache_img
    },
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    addItem () {
      this.options.push({
        code: String.fromCharCode(
          this.options[this.options.length - 1].code.charCodeAt(0) + 1
        ),
        title: '',
        img: '',
        isRight: ''
      })
    },
    changeCity () {
      this.options_province = citys(this.form.province)
      this.form.city = this.options_province[0]
    },

    pushImg (e) {
      if (e.target.tagName === 'IMG') {
        if (e.target.parentNode.children[2].src) {
          // e.target.parentNode.children[2].src = null
          // URL.revokeObjectURL(this.imgurl)
        }
        e.target.parentNode.children[1].click()
      }
    },
    getUrl (e) {
      if (e.target.files[0]) {
        this.imgurl = URL.createObjectURL(e.target.files[0])
        e.target.parentNode.children[2].src = this.imgurl
      }
    },
    hChange () {
      // 改变isright
      this.questionType === 1 ? this.options.forEach(i => i.isRight = this.radio == i.code ? 1 : 0) : this.options.forEach(i => i.isRight = this.checkList.includes(i.code) ? 1 : 0)
      // 改变图片地址
      document
        .querySelectorAll('ul li img')
        .forEach((cur, index) => (this.options[index].img = cur.src))
      if (this.$route.query.id) {
        createAPI('/questions/' + this.$route.query.id, 'put', {
          id: Number(this.$route.query.id),
          subjectID: this.form.subjectID,
          catalogID: this.form.catalogID,
          enterpriseID: this.form.enterpriseID,
          city: this.form.city,
          direction: String(this.form.direction),
          questionType: String(this.questionType),
          difficulty: String(this.difficulty),
          options: this.options,
          question: this.form.question,
          videoURL: this.videoURL,
          answer: this.form.answer,
          remarks: this.remarks,
          tags: this.tags.join(','),
          province: this.form.province
        })

        this.$router.push('/questions/list')
      } else {
        createAPI('/questions', 'post', {
          subjectID: this.form.subjectID,
          catalogID: this.form.catalogID,
          enterpriseID: this.form.enterpriseID,
          province: this.form.province,
          city: this.form.city,
          direction: String(this.form.direction),
          questionType: String(this.questionType),
          difficulty: String(this.difficulty),
          question: this.form.question,
          options: this.options,
          videoURL: this.videoURL,
          answer: this.form.answer,
          remarks: this.remarks,
          tags: this.tags.join(',')
        })

        this.$router.push('/questions/list')
      }
    }
  },
  watch: {
    questionType () {
      // 切换选项处理,做缓存
      if (this.questionType === 1) {
        this.cache = this.options.splice(4)
      } else if (this.cache) {
        this.cache.forEach((i) => this.options.push(i))
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.select {
  width: 460px;
}
::v-deep .ql-editor {
  height: 200px;
}
li {
  margin-bottom: 30px;
}
::v-deep .image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  border: dashed 1px gray;
  height: 100%;
  border-radius: 15px;
}
img {
  width: 100px;
  height: 100px;
  font-size: 15px;
  border: dashed 1px gray;
  display: inline-block;
  border-radius: 15px;
  transform: translate(28px, 35px);
  line-height: 100px;
}
.el-radio,
.el-checkbox {
  display: inline;
}
::v-deep .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
